import asyncio
import websockets
import logging

# 设置日志级别和格式
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

async def handle_connections(websocket, path):
    try:
        # 接收客户端发送的消息
        message = await websocket.recv()
        logging.info(f"Received from client: {message}")

        # 向客户端发送消息
        await websocket.send("Hello, client!")
        logging.info("Sent: Hello, client!")

        # 模拟多次发送数据
        for i in range(5):
            await websocket.send(f"Message {i}")
            logging.info(f"Sent: Message {i}")

        # 发送特定消息让客户端断开连接
        await websocket.send("bye")
        logging.info("Sent: bye")
    except Exception as e:
        logging.error(f"Error: {e}")

start_server = websockets.serve(handle_connections, "192.168.3.8", 8000)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()